﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using AqueleAjax.UI;

namespace AqueleAjax.UI.Controls
{
    [ParseChildren(true)]
    public class AutoComplete : TextBox, IAjaxControl
    {
        private AjaxMainControl _currentMainControl;

        /// <summary>
        /// Instância do AjaxMainControl inserido na página relacionada ao controle atual.
        /// </summary>
        public AjaxMainControl CurrentMainControl
        {
            get
            {
                if (this._currentMainControl == null)
                {
                    this._currentMainControl = AjaxMainControl.GetAjaxMainControl(this.Page);
                }

                return this._currentMainControl;
            }
        }

        private AutoCompleteResult _result;

        public AutoCompleteResult Result
        {
            get
            {
                if (this._result == null)
                {
                    this._result = new AutoCompleteResult();
                }

                return this._result; 
            }
            set { this._result = value; }
        }

        private string _dataKeyName;

        public string DataKeyName
        {
            get { return this._dataKeyName; }
            set { this._dataKeyName = value; }
        }

        [TemplateInstance(TemplateInstance.Single)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public virtual ITemplate ItemTemplate
        {
            get { return this.Result.ItemTemplate; }
            set { this.Result.ItemTemplate = value; }
        }

        [TemplateInstance(TemplateInstance.Single)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public virtual ITemplate SeparatorTemplate
        {
            get { return this.Result.SeparatorTemplate; }
            set { this.Result.SeparatorTemplate = value; }
        }

        public string GetCallbackResult()
        {
            return this.CurrentMainControl.GetCallbackResult();
        }

        public void RaiseCallbackEvent(string eventArgument)
        {
        }

        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);

            this.Result.DataBind();
            this.CurrentMainControl.Update(this.Result);
        }

        /// <summary>
        /// Faz a primeira configuração dos controles na página.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.InitAutoCompleteResult();
            this.SetCallbackEventReference();
            this.Result.ItemCommand += new AutoCompleteResultCommandEventHandler(this.Result_ItemCommand);
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.ClearOnChangeEvent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            this._result.RenderControl(writer);
        }

        protected override void LoadViewState(object savedState)
        {
            object[] viewState = (object[])savedState;

            base.LoadViewState(viewState[0]);
            this.DataKeyName = viewState[1].ToString();
        }

        protected override object SaveViewState()
        {
            object[] viewState = new object[2];

            viewState[0] = base.SaveViewState();
            viewState[1] = this.DataKeyName;

            return viewState;
        }

        /// <summary>
        /// Configura o evento que disparará a chamada assíncrona.
        /// </summary>
        private void SetCallbackEventReference()
        {
            this.Attributes.Add("onkeyup", AjaxMainControl.CallbackEventReference(this));
        }

        private void ClearOnChangeEvent()
        {
            this.Attributes.Remove("onchange");
            this.Attributes.Remove("onblur");
        }

        private void InitAutoCompleteResult()
        {            
            this._result.ID = string.Format(CultureInfo.CurrentCulture, "rsl{0}", this.ID);
            this.Controls.Add(this._result);

            this._result.AutoComplete = this;
        }

        private void Result_ItemCommand(object sender, AutoCompleteResultCommandEventArgs e)
        {
            //this.Text = e.Item.DataItem "Cuma?";
        }
    }
}
